package org.tinygroup.signature;

import java.util.List;

import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;

import org.tinygroup.logger.LogLevel;
import org.w3c.dom.Element;

public class SignatureChannelInterceptor extends AbstractSignChannelInterceptor {

	@Override
	protected String internalProcessor(Element element) throws Exception {
		CanonicalizationMethod cmethod = xmlSignatureFactory
				.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
						(C14NMethodParameterSpec) null);
		SignatureMethod smethod = xmlSignatureFactory.newSignatureMethod(
				SignatureMethod.RSA_SHA1, null);
		List<Reference> references = createReference();
		SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(cmethod,
				smethod, references);
		KeyInfo keyInfo = createKeyInfo(config);
		XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(
				signedInfo, keyInfo);
		LOGGER.logMessage(LogLevel.DEBUG, "创建XMLSignature完成.");
		DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
				element);
		xmlSignature.sign(signContext);
		LOGGER.logMessage(LogLevel.DEBUG, "执行签名操作完成.");
		return transform(element);
	}

}
